/**
 * tzdesk系统平台
 * moonvip_admin
 * com.tz.service.shoporder
 * IShoporderService.java
 * 创建人:小胡
 * 时间：2016年12月20日 11:25:23
 *
 */
package com.tz.service.shoporder.impl;

import com.tz.bean.ReceiptAddress;
import com.tz.bean.Shoporder;
import com.tz.bean.Store;
import com.tz.bean.User;
import com.tz.bean.*;
import com.tz.dao.paymentdetail.IPaymentdetailMapper;
import com.tz.dao.picture.IPictureMapper;
import com.tz.dao.receiptaddress.IReceiptAddressMapper;
import com.tz.dao.servicepicture.IServicePictureMapper;
import com.tz.dao.shoporder.IShoporderMapper;
import com.tz.dao.store.IStoreMapper;
import com.tz.dao.user.IUserMapper;
import com.tz.dao.wallet.IWalletMapper;
import com.tz.service.shoporder.IShoporderService;
import com.tz.util.KdniaoTrackQueryAPI;
import com.tz.util.StringHelper;
import com.tz.util.TmStringUtils;
import com.tz.util.weixinUtils.template.CommonOrder;
import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 商城订单管理serviceImpl
 * IShoporderService
 * 创建人:小胡
 * 时间：2016年12月20日 11:25:23
 * @version 1.0.0
 *
 */
@Service
public class ShoporderServiceImpl implements IShoporderService{

	@Resource
	private IShoporderMapper shoporderMapper;

	@Resource
	private IPaymentdetailMapper paymentdetailMapper;

	@Resource
	private IWalletMapper walletMapper;

	@Resource
	private IPictureMapper  pictureMapper;

	@Resource
	private IServicePictureMapper  servicePictureMapper;
	
	@Resource
	private IUserMapper userMapper;

	@Resource
	private IStoreMapper storeMapper;
	
	@Resource
	private IReceiptAddressMapper receiptAddressMapper;

	private static Logger logger = LoggerFactory.getLogger(ShoporderServiceImpl.class);

	private final  static  String key_suff = "orderpicture";
	private final  static  String key_suff2 = "checkportpicture/";

	@Override
	public List<Map<String , Object>> findShoporders(TzParams params){
		if(TmStringUtils.isEmpty(params.getOrder()))params.setOrder("o.create_time desc");
		List<Map<String , Object>> restList = shoporderMapper.findShoporders(params);
		try{
			if(!CollectionUtils.isEmpty(restList)){
				for(Map<String,Object> map : restList){
					if(CollectionUtils.isEmpty(map))
					continue;
					
					String nickName = (String)map.get("nickname");
					if(!StringUtils.isEmpty(nickName)){
						map.put("nickname", URLDecoder.decode(nickName, "utf8"));
					}
				}
			}
		}catch(Exception e){
			logger.error("");
		}
		return shoporderMapper.findShoporders(params);
	}

	@Override
	public int count(TzParams params) {
		return shoporderMapper.count(params);
	}

	@Override
	public HashMap<String ,Object> getShoporder(Integer id) {
		return shoporderMapper.getShoporder(id);
	}

	@Override
	public int save(Shoporder shoporder) {
		return shoporderMapper.save(shoporder);
	}

	@Override
	public int update(Shoporder shoporder) {
		return shoporderMapper.update(shoporder);
	}

	@Override
	public int delete(TzParams params) {
		return shoporderMapper.delete(params);
	}

	@Override
	public Map<String , Object> findShopOrderByOrderno(String orderno) {
		Map<String, Object> map = shoporderMapper.findShopOrderByOrderno(orderno);
		try{
			if(!CollectionUtils.isEmpty(map)){
				String nickName = (String)map.get("nickname");
				if(!StringUtils.isEmpty(nickName)){
					map.put("nickname", URLDecoder.decode(nickName, "utf8"));
				}
			}
		}catch(Exception e){
			logger.error("@findShopOrderByOrderno异常：{}",e.getMessage());
			e.printStackTrace();
		}
		return map;
	}

	@Override
	public List<Map<String, Object>> selectOrderDetailByOrderno(String orderno) {
		return shoporderMapper.selectOrderDetailByOrderno(orderno);
	}

	@Override
	public Map<String, Object> selectServiceOrderDetailByOrderno(String orderno) {
		return shoporderMapper.selectServiceOrderDetailByOrderno(orderno);
	}

	@Override
	public Map<String, Object> selectServiceOrderDetailByOrderno2(String orderno) {
		return shoporderMapper.selectServiceOrderDetailByOrderno2(orderno);
	}

	@Override
	public Map<String, Object> selectServiceInfo2(String orderno) {
		return shoporderMapper.selectServiceInfo2(orderno);
	}

	@Override
	public List<Map<String ,Object>> getAllRefurbishStatus() {
		return shoporderMapper.getAllRefurbishStatus();
	}

	//获取所有的商城订单状态
	@Override
	public List<Map<String ,Object>> getAllShopStatus(){
		return shoporderMapper.getAllShopStatus();
	}

	@Override
	//获取所有的检测订单状态
	public List<Map<String ,Object>> getAllTestingStatus(){
		return shoporderMapper.getAllTestingStatus();
	}

	@Override
	//获取所有的维修状态
	public List<Map<String, Object>> getAllRepairStatus() {
		return shoporderMapper.getAllRepairStatus();
	}

	//获取所有的回收订单状态
	@Override
	public List<Map<String, Object>> getAllRecycleStatus() {
		return shoporderMapper.getAllRecycleStatus();
	}

	@Override
	//获取所有的换款订单状态
	public List<Map<String ,Object>> getAllExChangeStatus(){
		return shoporderMapper.getAllExChangeStatus();
	}

	//查询每日分类订单的数量
	public  int getDayOrderNum(String type){
		return shoporderMapper.getDayOrderNum(type);
	}

	// 查询每日所有订单的数量
	@Override
	public int getDayAllOrderNum() {
		return shoporderMapper.getDayAllOrderNum();
	}

	//查询今日会员新增数量
	@Override
	public int getDayUserNum() {
		return shoporderMapper.getDayUserNum();
	}


	//根据订单号获取serviceId
	@Override
	public int getServiceIdByorderno(String orderno) {
		return shoporderMapper.getServiceIdByorderno(orderno);
	}

	//保存检测报告
	public void saveCheckport(String orderNo ,String type ,String checkreport, String[] checkreportUrl,Integer serviceId,String getway) throws IOException {
		Picture picture = null;
		String url  = null;
		ServicePicture servicePicture = null;
		//将检测报告的图片保存到service_picture表中 type规定为007，同时 检测报告的内容保存到service表中checkreport
		for (String imgurl:checkreportUrl){
			url =  StringHelper.uploadAndgetUrl(key_suff, imgurl);
			picture = new Picture();
			picture.setUrl(url);
			pictureMapper.save(picture);
			servicePicture = new ServicePicture();
			servicePicture.setPictureId(picture.getId());
			servicePicture.setServiceId(serviceId);
			servicePicture.setType("007");
			servicePictureMapper.save(servicePicture);
		}

		//更新service 保存检测报告字段
		com.tz.bean.Service service = new com.tz.bean.Service(serviceId ,checkreport ,new Date());
		shoporderMapper.updateService(service);
		//更新订单状态的为 待翻新(已检测)
		String status = "";
		if("001".equals(type)){
			status =  "001005";//等待翻新
		}
		if("002".equals(type)){
			status =  "002007";//等待维修
		}
		if("003".equals(type)){
			if("002".equals(getway)){
				status =  "003007";//等待客户取货
			}else{
				status =  "003006";//检测服务 填完检测报告就可发货了 待发货
			}
		}
		if("004".equals(type)){
			status =  "004004";//待定价
		}
		if("005".equals(type)){
			status =  "005004";//待定价
		}
		shoporderMapper.update(new Shoporder(orderNo , status));
	}

	@Override
	public int updateCheckport(com.tz.bean.Service service, int[] delIds, String[] addImgs) throws IOException {
		//添加图片
		Picture picture = null;
		String url  = null;
		ServicePicture servicePicture = null;
		for (String imgurl:addImgs){
			if(!("0").equals(imgurl)){
				url =  StringHelper.uploadAndgetUrl(key_suff, imgurl);
				picture = new Picture();
				picture.setUrl(url);
				pictureMapper.save(picture);
				servicePicture = new ServicePicture();
				servicePicture.setPictureId(picture.getId());
				servicePicture.setServiceId(service.getId());
				servicePicture.setType("007");
				servicePictureMapper.save(servicePicture);
			}
		}
		//参数之前的图片
		for(int id:delIds){
			if(id!=0){
				servicePictureMapper.delete(id);
			}
		}
		//更新service 保存检测报告字段
		service.setUpdateTime(new Date());
		shoporderMapper.updateService(service);
		return 0;
	}


	@Override
	public int saveOrderPicture(OrderPicture orderPicture) {
		return shoporderMapper.saveOrderPicture(orderPicture);
	}

	@Override
	public List<HashMap<String , Object>> findAllexpressCompanies() {
		return shoporderMapper.findAllexpressCompanies();
	}

	//保存拍照邮寄信息 ，保存 图片到picture表，保存订单_图片中间，更新订单表
	@Override
	public void saveOrderPicture(Shoporder shoporder, String[] imgurls) throws IOException {
		for(int i=0;i<imgurls.length;i++){
			//获得七牛子商品图片外链
			String imgurl = StringHelper.uploadAndgetUrl(key_suff , imgurls[i]);
			Picture picture = new Picture(imgurl);
			shoporderMapper.savePicture(picture);
			shoporderMapper.saveOrderPicture(new OrderPicture(shoporder.getOrderno() , picture.getId()));
		}
		if("001".equals(shoporder.getType())){
			shoporder.setShoporderstatuscode("001007");
			shoporderMapper.update(shoporder);
		}
		if("002".equals(shoporder.getType())){
			shoporder.setShoporderstatuscode("002009");
			shoporderMapper.update(shoporder);
		}
		if("003".equals(shoporder.getType())){
			shoporder.setShoporderstatuscode("003007");
			shoporderMapper.update(shoporder);
		}
		//回收退货才需要 拍照邮寄返回商品
		if("004".equals(shoporder.getType())){
			shoporder.setShoporderstatuscode("004010");
			shoporderMapper.update(shoporder);
		}
		if("005".equals(shoporder.getType())){
			shoporder.setShoporderstatuscode("005009");
			shoporderMapper.update(shoporder);
		}
		if("006".equals(shoporder.getType())){
			shoporder.setShoporderstatuscode("003");
			shoporderMapper.update(shoporder);
		}

	}

	@Override
	public JSONObject   getOrderTracesByJson(Shoporder order , int mark) throws Exception {
		JSONObject result = null;
		if(mark==0){
			result = KdniaoTrackQueryAPI.getOrderTracesByJson((String)order.getUserlogisticsnocomp() , (String)order.getUserlogisticsno());
		}else{
			result = KdniaoTrackQueryAPI.getOrderTracesByJson((String)order.getLogisticsnocomp() , (String)order.getLogisticsno());
		}
		return result;
	}

	/**
	 * 定价
	 * 根据orderno找到service
	 * 更新service中的定价字段 aturalprice
	 * 更新订单表中的totalprice字段
	 * @param orderno
	 * @param type
	 * @return
	 */
	@Override
	public void updateFixPrice(String orderno ,String type ,Double aturalprice, String openid) {
		//根据订单号查询得到serviceid
		int serviceId = shoporderMapper.getServiceIdByorderno(orderno);
		//更新service 保存定价价格 aturalprice字段
		com.tz.bean.Service service = new com.tz.bean.Service(serviceId ,aturalprice ,new Date());
		shoporderMapper.updateService(service);
		//更新订单表的totalPrice字段
		String status = "";
		if("002".equals(type)){  //待确认，客户是否确认维修
			status = "002002";
		}
		if("004".equals(type)){
			status = "004005";  //待确认 客户是否确认回收
		}
		if("005".equals(type)){
			status = "005005";  //待确认 客户是否确认换款
		}
		shoporderMapper.update(new Shoporder(orderno , aturalprice, status , new Date()));
	}

	@Override
	public String getlogisticCompany(String logisticno) {
		return shoporderMapper.getlogisticCompany(logisticno);
	}

	@Override
	public void updateConfirmRecycleMoney(Shoporder shoporder, String backUsername){
		//查询账户信息
		Wallet wallet = walletMapper.getWalletByUserId(shoporder.getUserId());
		//新增账户明细记录
		Paymentdetail paymentdetail = new Paymentdetail();
		paymentdetail.setWalletNo(wallet.getWalletno());
		if("006".equals(shoporder.getType())){
			paymentdetail.setChangeMoney(shoporder.getActualpayprice());
		} else{
			paymentdetail.setChangeMoney(shoporder.getTotalprice());
		}
		String type = "";
		String orderStatus = "";
		if("004".equals(shoporder.getType())){
			type = "回收";
			orderStatus = "004007";
		}
		if("005".equals(shoporder.getType())){
			type = "换款";
			orderStatus = "005015";
		}
		if("006".equals(shoporder.getType())){
			type = "商城退款";
			orderStatus = "010";
		}
		paymentdetail.setMemo("来自"+type+"订单:"+shoporder.getOrderno() + "，操作人："+backUsername);
		Double balance = wallet.getBalance() + paymentdetail.getChangeMoney();
		paymentdetail.setBalance(balance);
		paymentdetailMapper.save(paymentdetail);
		//更新账户信息
		wallet.setBalance(balance);
		wallet.setUpdateTime(new Date());
		walletMapper.update(wallet);
		//更新订单状态
		shoporder.setShoporderstatuscode(orderStatus);
		shoporderMapper.update(shoporder);
	}

	public List<HashMap<String, Object>> getGoodDetailByOrdeno(String orderno){
		return  shoporderMapper.getGoodDetailByOrdeno(orderno);
	}

	/**
	 * 查询所有的服务订单的图片
	 */
	@Override
	public List<HashMap<String, Object>> getAllServicepictures(String orderno) {
		return shoporderMapper.getAllServicepictures(orderno);
	}

	@Override
	public List<HashMap<String, Object>> getcheckportServicepictures(String orderno) {
		return shoporderMapper.getcheckportServicepictures(orderno);
	}

	@Override
	public Map<String, Object> selectBuyInfo(String orderno) {
		return shoporderMapper.selectBuyInfo(orderno);
	}

	@Override
	public HashMap<String, Object>  getReportByOrderno(String orderno){
		return shoporderMapper.getReportByOrderno(orderno);
	}

	public HashMap<String, Object> getLogist(String orderno){
		return shoporderMapper.getLogist(orderno);
	}

	@Override
	public int updateService(com.tz.bean.Service service) {
		return shoporderMapper.updateService(service);
	}


	@Override
	public HashMap<String, Object> getcheckportServiceId(String orderno) {
		return shoporderMapper.getcheckportServiceId(orderno);
	}

	public HashMap<String, Object>  getMetal(String orderno){
		return shoporderMapper.getMetal(orderno);
	}

	public HashMap<String, Object>  getDiamond(String orderno){
		return  shoporderMapper.getDiamond(orderno);
	}

	public HashMap<String, Object>  getStoreInfo(String orderno){
		return shoporderMapper.getStoreInfo(orderno);
	}

	public List<HashMap<String, Object>>  chartcheckedGood(Integer serviceId){
		return shoporderMapper.chartcheckedGood(serviceId);
	}

	@Override
	public List<HashMap<String, Object>> getAllcheckpictures(Integer serviceId) {
		return shoporderMapper.getAllcheckpictures(serviceId);
	}

	@Override
	public String getNickname(String openid) {
		String nickName = shoporderMapper.getNickname(openid);
		try{
			if(!StringUtils.isEmpty(nickName)){
				nickName = URLDecoder.decode(nickName, "utf8");
			}
		}catch(Exception e){
			logger.error("@getNickname异常：{}",e.getMessage());
			e.printStackTrace();
		}
		return nickName;
	}

	public String getRemark(Integer exId){
		return  shoporderMapper.getRemark(exId);
	}

	@Override
	public CommonOrder getCommonOrder(String orderno) {
		try{

			CommonOrder order = new CommonOrder();
			Map<String, Object> shopOrder = shoporderMapper.findShopOrderByOrderno(orderno);
			if(shopOrder == null){
				logger.info("订单号{}查不到相关的订单信息。",orderno);
				return null;
			}
			order.setCustomerConfirm(true);
			order.setExpressCode((String)shopOrder.get("logisticsno"));//快递单号
			//取货方式，默认为邮寄
			order.setGetWay(shopOrder.get("getway") == null ? "001" : shopOrder.get("getway").toString());
			//发货方式，默认邮寄
			order.setSendWay(shopOrder.get("sendway") == null ? "002" : shopOrder.get("sendway").toString());
			order.setOrderNo(shopOrder.get("orderno").toString());
			order.setOrderType(shopOrder.get("type").toString());
			//001翻新002维修003检测004回收005换款006商城007充值
			switch(shopOrder.get("type").toString()){
			case "001" : order.setOrderTypeDesc("翻新");break;
			case "002" : order.setOrderTypeDesc("维修");break;
			case "003" : order.setOrderTypeDesc("检测");break;
			case "004" : order.setOrderTypeDesc("回收");break;
			case "005" : order.setOrderTypeDesc("换款");break;
			case "006" : order.setOrderTypeDesc("商城");break;
			case "007" : order.setOrderTypeDesc("充值");break;
			}
			
			order.setPrice(shopOrder.get("totalprice")== null?"0.0":shopOrder.get("totalprice").toString());
			
			//收货人地址
			String receipt_address_id =  shopOrder.get("receipt_address_id") == null ? "0" : shopOrder.get("receipt_address_id").toString();
			if(!StringUtils.isEmpty(receipt_address_id)){
				Map<String, Object> receiptAddress = receiptAddressMapper.getReceiptAddress(Integer.parseInt(receipt_address_id));
				if(receiptAddress != null){
					order.setReceiptAddress((receiptAddress.get("province_name")==null?"":receiptAddress.get("province_name").toString())
							.concat(receiptAddress.get("city_name")==null?"":receiptAddress.get("city_name").toString())
							.concat(receiptAddress.get("country_name")==null?"":receiptAddress.get("country_name").toString())
							.concat(receiptAddress.get("detail_info")==null?"":receiptAddress.get("detail_info").toString()));
				}
			}
			
			//商家地址
			order.setStoreAddress((String)shopOrder.get("storeAddress"));
			order.setStoreContactName("金小六");
			
			//查找用户openId
			int userId = Integer.parseInt(shopOrder.get("userId").toString());
			User user = userMapper.getUserInfoById(userId);
			if(user != null){
				order.setOpenId(user.getOpenid());
			}
			
			order.setVerified(true);//默认描述属实
			
			order.setOrderStatus((String)shopOrder.get("shoporderstatusCode"));
			
			return order;
		
		}catch(Exception e){
			logger.error("组装CommonOrder时出错：{}",e.getMessage());
			return null;
		}
	}



}
